package com.forest.gissingle.sql;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import com.forest.gissingle.bean.LatBean;
import com.forest.gissingle.bean.SqlDataBean;

import android.content.Context;

public class DBUtils {

	/**
	 * 将bean转化为string显示
	 * 
	 * @param sqlBean
	 * @return
	 */
	public static StringBuilder showSqlBean(SqlDataBean sqlBean) {
		StringBuilder sb = new StringBuilder();
		sb.append("Region=");
		sb.append(sqlBean.getRegion());
		sb.append("\n");
		sb.append("number=");
		sb.append(sqlBean.getNumber());
		sb.append("\n");
		try {
			sb.append("Center:");
			sb.append("lat=" + sqlBean.getCenter().getLatitude() + "long="
					+ sqlBean.getCenter().getLongitude());
			sb.append("\n");
		} catch (Exception e) {
			sb = new StringBuilder();
			return sb.append("Center无数值");
		}
		ArrayList<LatBean> lats = sqlBean.getLats();
		sb.append("lats:\n");
		for (LatBean latBean : lats) {
			sb.append("lat=" + latBean.getLatitude() + "long="
					+ latBean.getLongitude());
			sb.append("\n");
		}
		return sb;
	}

	public static String getDBPath(Context context) {
		String path = context.getDir("", Context.MODE_PRIVATE).getParent()
				+ "/databases";
		String dbpath = path + "/" + DBManager.DB_TOTAL;
		return dbpath;
	}

	/**
	 * copy asset to db
	 * 
	 * @param dbname
	 *            目标数据库名称
	 * @return size
	 */
	public static long copyDBFromAsset(Context context) {
		String path = context.getDir("", Context.MODE_PRIVATE).getParent()
				+ "/databases";
		String dbpath = path + "/" + DBManager.DB_TOTAL;
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		long copySizes = 0;
		try {
			BufferedInputStream bin = new BufferedInputStream(context
					.getAssets().open("AreaData"));
			BufferedOutputStream bout = new BufferedOutputStream(
					new FileOutputStream(new File(dbpath)));
			int b = 0, i = 0;
			while ((b = bin.read()) != -1) {
				bout.write(b);
				i++;
			}
			bout.flush();
			bin.close();
			bout.close();
			copySizes = i;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return copySizes;
	}
}
